import React, { useState, useEffect } from 'react';
import { Button, Icon, message, Upload } from 'antd';
import COMMONATION from 'service/apis/commonAction';
import uploadUrl from 'dic/uploadUrl';
import { connect } from 'dva';
import pic from 'dic/pic';
import * as qiniu from 'qiniu-js'
import { randomString } from 'utils/format'
import AWS from 'aws-sdk'
import './index.styl';


function UploadPic({ dispatch, commonAction: { uploadInfo }, getImgSrc, editImg }) {
  const [imgSrc, setImgSrc] = useState('')
  useEffect(() => {
    dispatch({
      type: 'commonAction/getToken',
    });
  }, [dispatch]);

  useEffect(() => {
    setImgSrc(editImg);
  }, [editImg]);

  const localProps = {
    name: 'file',
    accept: ".jpg,.png,.jpeg",
    action: COMMONATION.UPLOAD_IMG,
    headers: {
      authorization: 'Bearer ' + uploadInfo.token,
    },
    showUploadList: false,
    beforeUpload(file) {
      const { size } = file;
      const isLt10M = size / 1024 / 1024 <= 10;
      if (!isLt10M) {
        message.error('图片大小不超过10MB!');
      }
      return isLt10M;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        const { code, data } = info.file.response;
        if (code === '000000') {
          message.success(`图片上传成功`);
          setImgSrc(data.url);
          getImgSrc(data.url);
        }
      } else if (info.file.status === 'error') {
        message.error(`图片上传失败`);
      }
    }
  };

  const awsProps = {
    accept: ".jpg,.png,.jpeg",
    showUploadList: false,
    beforeUpload(file) {
      const { size } = file;
      const isLt10M = size / 1024 / 1024 <= 10;
      if (!isLt10M) {
        message.error('图片大小不超过10MB!');
      }
      return isLt10M;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        AWS.config.endpoint = 'https://oss-cn-north-2.unicloudsrv.com'
        AWS.config.region = "cn-beijing-1"
        AWS.config.accessKeyId = uploadInfo.accessKeyId
        AWS.config.secretAccessKey = uploadInfo.secretAccessKey
        AWS.config.sessionToken = uploadInfo.token
        AWS.config.s3ForcePathStyle = true
        const s3 = new AWS.S3()
        const fileName = randomString(16) + pic.matchObj[info.file.originFileObj.type]
        s3.putObject({
          Bucket: 'chengdufensuo',
          Key: fileName,
          Body: info.file.originFileObj
        }, (err, data) => {
          if (err) {
            message.error(`图片上传失败`);
          } else {
            message.success(`图片上传成功`);
            setImgSrc(`https://chengdufensuo.oss-cn-north-2.unicloudsrv.com/${fileName}`);
            getImgSrc(`https://chengdufensuo.oss-cn-north-2.unicloudsrv.com/${fileName}`);
          }
        })
      } else if (info.file.status === 'error') {
        message.error(`图片上传失败`);
      }
    },
  };

  const qiniuProps = {
    showUploadList: false,
    beforeUpload(file) {
      const { type, size } = file;
      const isType = type === 'image/png' || type === 'image/jpg' || type === 'image/jpeg';
      if (!isType) {
        message.error('只能上传 JPG/JPEG/PNG 格式的图片!');
      }
      const isLt10M = size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('图片大小不超过10MB!');
      }
      return isType && isLt10M;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log('uploading')
      }
      if (info.file.status === 'done') {
        const observable = qiniu.upload(info.file.originFileObj, info.file.name, uploadInfo.token, {
          fname: "",
          params: {},
          mimeType: ["image/png", "image/jpeg", "image/jpg"]
        }, {
          useCdnDomain: true,
        })
        observable.subscribe({
          next(res) {
            console.log('res', res)
          },
          error(err) {
            console.log('err', err)
          },
          complete(res) {
            setImgSrc(uploadUrl.qiniu + res.key);
            getImgSrc(uploadUrl.qiniu + res.key);
          }
        })
      } else if (info.file.status === 'error') {
        message.error(`图片上传失败`);
      }
    },
  };
  const propsData = uploadInfo.fileService === "Local" ? localProps : (uploadInfo.fileService === 'unicloud' ? awsProps : qiniuProps)
  return (
    <div className="uploadPic">
      <div className="flexWrapper">
        <div>
          <Upload {...propsData}>
            <Button className="btn fix-btn">
              <Icon type="upload" /> 上传
            </Button>
          </Upload>
        </div>
        <div className="tip">
          请上传一张设主图，建议比例为16/9;支持格式：jpg、jpeg、png，不超过10M。
        </div>
      </div>
      <Upload {...propsData} className='avatar-uploader'>
        {imgSrc ? <img src={imgSrc} alt="avatar" style={{ width: '100%' }} /> : ''}
      </Upload>
    </div>
  );
}

export default connect(({ commonAction }) => ({
  commonAction,
}))(UploadPic);
